package com.lei.springbootpractice.controller;

import com.lei.springbootpractice.pojo.OrdersPojo;
import com.lei.springbootpractice.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/orders")
public class OrdersController {
    @Autowired
    OrdersService ordersService;

    @GetMapping
    public List<OrdersPojo> getAllOrders(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        return ordersService.getAllOrders(status, startDate, endDate);
    }

    @GetMapping("/{userId}")
    public List<OrdersPojo> getOrders(@PathVariable String userId) {
        return ordersService.getOrdersByUserId(userId);
    }

    @PostMapping
    public boolean createOrder(@RequestBody OrdersPojo order) {
        return ordersService.createOrder(order);
    }

    @DeleteMapping("/{orderId}")
    public boolean cancelOrder(@PathVariable String orderId) {
        return ordersService.cancelOrder(orderId);
    }

    @PostMapping("/from-cart/{userId}")
    public Map<String, Object> createOrderFromCart(@PathVariable String userId, @RequestBody Map<String, Object> requestBody) {
        Map<String, Object> response = new HashMap<>();
        try {
            System.out.println("开始为用户 " + userId + " 创建订单");
            System.out.println("完整请求体数据: " + requestBody);

            // 详细记录addressId
            String addressId = (String) requestBody.get("addressId");
            System.out.println("接收到的addressId: " + addressId);
            System.out.println("addressId类型: " + (addressId != null ? addressId.getClass().getName() : "null"));

            if (addressId == null || addressId.isEmpty()) {
                System.err.println("addressId为空或未提供");
                throw new RuntimeException("请选择收货地址");
            }

            // 验证addressId格式
            if (!addressId.matches("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$")) {
                System.err.println("addressId格式无效: " + addressId);
                throw new RuntimeException("收货地址ID格式无效");
            }
            boolean result = ordersService.createOrderFromCart(userId, addressId);
            if (result) {
                System.out.println("订单创建成功，用户ID: " + userId);
                List<OrdersPojo> orders = ordersService.getOrdersByUserId(userId);
                OrdersPojo latestOrder = orders.get(orders.size() - 1);

                response.put("success", true);
                response.put("message", "订单创建成功");
                response.put("data", latestOrder);
            } else {
                System.out.println("订单创建失败，用户ID: " + userId);
                response.put("success", false);
                response.put("message", "订单创建失败，请重试");
            }
        } catch (RuntimeException e) {
            System.err.println("创建订单业务异常: " + e.getMessage());
            response.put("success", false);
            response.put("message", e.getMessage());
            response.put("errorType", "business");
        } catch (Exception e) {
            System.err.println("创建订单系统异常: " + e.getMessage());
            response.put("success", false);
            response.put("message", "系统繁忙，请稍后再试");
            response.put("errorType", "system");
        }
        return response;
    }

    @GetMapping("/detail/{orderId}")
    public OrdersPojo getOrderDetail(@PathVariable String orderId) {
        return ordersService.getOrderDetail(orderId);
    }

    @PostMapping("/pay/{orderId}")
    public Map<String, Object> payOrder(@PathVariable String orderId, @RequestBody Map<String, String> paymentInfo) {
        Map<String, Object> response = new HashMap<>();
        try {
            String paymentType = paymentInfo.get("paymentType");
            String paymentAccount = paymentInfo.get("paymentAccount");

            boolean result = ordersService.payOrder(orderId, paymentType, paymentAccount);
            if (result) {
                response.put("success", true);
                response.put("message", "支付成功");
            } else {
                response.put("success", false);
                response.put("message", "支付失败");
            }
        } catch (RuntimeException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }

    @PostMapping("/update-status/{orderId}")
    public Map<String, Object> updateOrderStatus(
            @PathVariable String orderId,
            @RequestBody Map<String, String> statusInfo) {
        Map<String, Object> response = new HashMap<>();
        try {
            String status = statusInfo.get("status");
            String shippingCompany = statusInfo.get("shippingCompany");
            String shippingNo = statusInfo.get("shippingNo");

            boolean result = ordersService.updateOrderStatus(orderId, status, shippingCompany, shippingNo);
            if (result) {
                response.put("success", true);
                response.put("message", "订单状态更新成功");
            } else {
                response.put("success", false);
                response.put("message", "订单状态更新失败");
            }
        } catch (RuntimeException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }

    @PostMapping("/confirm-receipt/{orderId}")
    public Map<String, Object> confirmReceipt(@PathVariable String orderId) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean result = ordersService.confirmReceipt(orderId);
            if (result) {
                response.put("success", true);
                response.put("message", "确认收货成功");
            } else {
                response.put("success", false);
                response.put("message", "确认收货失败");
            }
        } catch (RuntimeException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }

    @PostMapping("/submit-review/{orderId}")
    public Map<String, Object> submitReview(
            @PathVariable String orderId,
            @RequestBody Map<String, Object> reviewInfo) {
        Map<String, Object> response = new HashMap<>();
        try {
            String productId = (String) reviewInfo.get("productId");
            Integer rating;
            if (reviewInfo.get("rating") instanceof String) {
                rating = Integer.parseInt((String) reviewInfo.get("rating"));
            } else {
                rating = (Integer) reviewInfo.get("rating");
            }
            String comment = (String) reviewInfo.get("comment");

            OrdersService.ReviewResult result = ordersService.submitReview(orderId, productId, rating, comment);

            if (result.isSuccess()) {
                response.put("success", true);
                response.put("message", "评价提交成功");
            }else{
                response.put("success", false);
                response.put("message", result.getMessage());
            }
        } catch (NumberFormatException e) {
            response.put("success", false);
            response.put("message", "评分格式不正确");
        } catch (RuntimeException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }
}
